package com.yunshipei.common;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.yunshipei.common.exception.UserAuthException;
import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.net.api.LoginAuthApi;
import com.yunshipei.common.net.converter.JsonConverterFactory;
import com.yunshipei.core.common.DeviceInfo;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.utils.EncUtils;

import org.chromiun.net.GURLUtils;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * 第二步登录逻辑，此登录除了手动输入输入用户名密码登录外，自动登录也会调用此类的方法
 */
public class LoginManager {

    private DeviceInfo mDeviceInfo;
    private String mCompanyID = "";
    private String mManagerServer = "";
    private LoginAuthApi mLoginAuthApi;

    private SharedPreferences mCommonPreferences;
    private SharedPreferences mNoClearPreferences;

    private Context context;

    public LoginManager(Context context) {
        this.context = context;
        mDeviceInfo = new DeviceInfo(context);
        mCommonPreferences = YspPreferences.getInstance().getSharedPreferences();
        mNoClearPreferences = context.getSharedPreferences(Globals.NO_CLEAR_SHP, Context.MODE_PRIVATE);
        mManagerServer = mNoClearPreferences.getString(Globals.MANUAL_BASE_URL, "");
        if (TextUtils.isEmpty(mManagerServer)) {
            mManagerServer = mNoClearPreferences.getString(Globals.SP_HUB_GET_SERVER, "");
        }
        if (mManagerServer.endsWith("/")) {
            mManagerServer = mManagerServer.substring(0, mManagerServer.length() - 1);
        }
        mCompanyID = mNoClearPreferences.getString(Globals.SP_COMPANY_ID, "");
        String mProxy = mNoClearPreferences.getString(Globals.MANUAL_PROXY, "");
        int mProxyPort = mNoClearPreferences.getInt(Globals.MANUAL_PROXY_PORT, 0);
        if (TextUtils.isEmpty(mProxy) || mProxyPort == 0) {
            mProxy = mNoClearPreferences.getString(Globals.SP_HUB_GET_PROXY_IP, "");
            mProxyPort = mNoClearPreferences.getInt(Globals.SP_HUB_GET_PROXY_PORT, 0);
        }
        EnterClient.getInstances().initManagerClient(mManagerServer + "/v2/newLogin", mProxy, mProxyPort);
        OkHttpClient client = EnterClient.getInstances().getManagerClient();
        mLoginAuthApi = new Retrofit.Builder().client(client).baseUrl(mManagerServer).addConverterFactory(JsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build().create(LoginAuthApi.class);
        EnterConfig.getInstance().setManagerServer(mManagerServer);
    }

    //1、第二部根据上一步的企业ID，用户名，密码登录
    public Flowable<MainExtraBean> createLoginFlowable(final String userName, final String password) {
        return Flowable.just(mManagerServer).flatMap(new Function<String, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(String s) throws Exception {
                long timeStamp = System.currentTimeMillis();
                JSONObject sdkSumSrc = new JSONObject();
                sdkSumSrc.put("sdk", mCompanyID);
                sdkSumSrc.put("deviceId", userName);
                sdkSumSrc.put("timestamp", timeStamp);
                String sdkSum = GURLUtils.getSDKSum(sdkSumSrc.toString());
                return mLoginAuthApi.authUser(mCompanyID, userName, password, timeStamp, mDeviceInfo.allInfo(), sdkSum);
            }
        }).flatMap(new Function<JSONObject, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(JSONObject jsonObject) throws Exception {
                int status = jsonObject.optInt("status");
                if (status != 1) {
                    return Flowable.error(new UserAuthException(jsonObject.optString("message", "未知接口异常，请联系管理员")));
                }
                return XCloudSDKManager.getInstance().prepareXCloudData(context, mManagerServer, jsonObject);
            }
        }).flatMap(new Function<JSONObject, Publisher<MainExtraBean>>() {
            @Override
            public Publisher<MainExtraBean> apply(JSONObject jsonObject) throws Exception {
                return new ProfileHandler(context, jsonObject, mManagerServer, password).start();
            }
        });
    }

    //2、MainActivity里面的自动登录逻辑
    public Flowable<MainExtraBean> autoLogin() {
        String userName = mCommonPreferences.getString(Globals.USER_NAME, "");
        String password = EncUtils.decrypt(mCommonPreferences.getString(Globals.UUID, ""), mCommonPreferences.getString(Globals.PASSWORD, ""));
        return createLoginFlowable(userName, password);
    }
}
